package com.doule.farmerassistant.task;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.doule.farmerassistant.MyService;
import com.doule.farmerassistant.R;
import com.doule.farmerassistant.DeathConfig;
import com.doule.farmerassistant.ToolHelper;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * TaskControlActivity class.
 * 
 * @author riguang
 * 
 */
public class TaskControlActivity extends Activity implements MyService.NotifyListener {
    /**
     * Task id.
     */
    private String mTaskId;
    /**
     * Authentication token.
     */
    private String mToken;

    /**
     * ProgressBar.
     */
    private ProgressBar doingTaskPB;
    
    /**
     * Doing task View.
     */
    private LinearLayout doingTaskLL;

    // private TextView mtvAdv;

    // private StartOrStopTask mStartOrStopTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_control_panel);

        findViewById(R.id.btn_start).setOnClickListener(onClickListener);
        findViewById(R.id.btn_stop).setOnClickListener(onClickListener);
        doingTaskPB = (ProgressBar) findViewById(R.id.progressBar_doing_task);
        doingTaskLL = (LinearLayout) findViewById(R.id.ll_doing_task);

        // mtvAdv = (TextView) findViewById(R.id.tv_RssFeed);
        // mtvAdv.setMovementMethod(new ScrollingMovementMethod());
        // mtvAdv.setText("123456789987654321123456789987654321qazwsxedcrfvtgbyhnujmiklop");
        mToken = getIntent().getStringExtra("tk");
        mTaskId = getIntent().getStringExtra("id");

        updateTaskStatus();

        MyService.getInstance().setNotifyListener("/taskstatus", this);
    }
    
    /**
     * update status.
     */
    private void updateTaskStatus() {
        TaskFragment f = TaskFragment.getInstance();
        if (f == null) {
            return;
        }
        
        TaskDetail td = f.getTask(mTaskId);
        
        TextView typeView = (TextView) findViewById(R.id.tv_type);
        typeView.setText(td.getType());

        TextView nameView = (TextView) findViewById(R.id.tv_name);
        nameView.setText(td.getName());

        TextView batchTypeView = (TextView) findViewById(R.id.tv_batch_type);
        batchTypeView.setText(td.getPerbatch());

        TextView durationView = (TextView) findViewById(R.id.tv_duration);
        durationView.setText(td.getDuration());
        
        TextView status = (TextView) findViewById(R.id.tv_status);
        status.setText(td.getStatusString());
    }
    
    @Override
    public void onDestroy() {
        MyService.getInstance().removeNotifyListener("/taskstatus", this);
        super.onDestroy();
    }
    /**
     * Start or stop task.
     * 
     * @param isStart
     *            true if is being to start task, else false
     */
    private void startOrStopTask(final boolean isStart) {
        StartOrStopTask startOrStopTask = new StartOrStopTask(isStart);
        startOrStopTask.execute((Void) null);
    }

    /**
     * Button on click listener.
     */
    private OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.btn_start:
                startOrStopTask(true);
                break;
            case R.id.btn_stop:
                startOrStopTask(false);
                break;
            default:
                break;
            }

        }

    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.control_panel, menu);
        return true;
    }

    /**
     * StartOrStopTask class.
     * 
     * @author riguang
     * 
     */
    final class StartOrStopTask extends AsyncTask<Void, Void, Boolean> {
        // private String mToken;
        /**
         * Http request error.
         */
        private ToolHelper.HttpError error;

        /**
         * Server url.
         */
        private String mServerUrl;

        /**
         * Http request result.
         */
        private String mResultMsg;

        /**
         * true if is start task, false if is stop task.
         */
        private boolean mIsStart;

        /**
         * Constructor.
         * 
         * @param isStart
         *            true if is start task.
         */
        private StartOrStopTask(final boolean isStart) {
            final String serverUrl = DeathConfig.getServerUrl();
            mIsStart = isStart;
            if (isStart) {
                mServerUrl = serverUrl + "/startTask";
            } else {
                mServerUrl = serverUrl + "/stopTask";
            }
        }

        /**
         * Http request to start or stop task.
         * 
         * @return true if start or stop success.
         */
        private boolean sartOrStopTask() {
            // String serverUrl = DeathConfig.server_url;
            // Log.e("UserLoginTask", "token: " + mToken);
            HttpPost request = new HttpPost(mServerUrl);
            request.setHeader("content-type", "application/json");
            request.setHeader("tk", mToken);
            request.setHeader("taskId", mTaskId);

            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            try {
                HttpResponse resp = client.execute(request);
                error = ToolHelper.errorParse(TaskControlActivity.this, resp);
                if (error != null) {
                    return false;
                }
                
                HttpEntity entity = resp.getEntity();
                mResultMsg = EntityUtils.toString(entity, "UTF-8");

                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
            return false;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (sartOrStopTask()) {
                return true;
            }

            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            // mStartOrStopTask = null;

            String msg = "";
            if (success) {
                if (mResultMsg == null || mResultMsg.equals("")) {
                    if (mIsStart) {
                        msg = getString(R.string.start_success);
                    } else {
                        msg = getString(R.string.stop_success);
                    }
                } else {
                    msg = mResultMsg;
                }
            } else {
                msg = error.getMsg();
            }

            Toast.makeText(TaskControlActivity.this, msg, Toast.LENGTH_LONG)
                    .show();
        }
        // @Override
        // protected void onCancelled() {
        // // mStartOrStopTask = null;
        // // showProgress(false);
        // }
    }

    @Override
    public void onJSONNotify(JSONObject jobject) {
        try {
            String taskId = jobject.getString("taskid");
            if (mTaskId.equals(taskId)) {
                updateTaskStatus();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
